import WxRequest from "./request";
import { env } from "./env";

const instance = new WxRequest({
  baseURL: env.baseURL,
  timeout: 15000,
});

//   配置请求拦截器
instance.interceptors.request = (config) => {
  const value = wx.getStorageSync("token")
  if (value) {
    config.header["token"] = value;
  } else {
  }
  return config;
};

//   配置响应拦截器
instance.interceptors.response = (response) => {
  const { isSuccess, data } = response;
  if (!isSuccess) {
    wx.showToast({
      title: "网络异常重试",
      icon: "error",
    });

    return response;
  }

  switch (data.code) {
    case 200:
      return data;
    case 208:
      wx.showModal({
        content: "鉴权失败，请重新登录",
        showCancel: false,
        complete: (res) => {
          if (res.confirm) {
            wx.clearStorage({
              key: "token",
            });

            wx.navigateTo({
              url: "/pages/login/login",
            });
          }
        },
      });

      return Promise.reject(response);

    default:
      wx.showToast({
        title: "程序出现异常，请联系客服或稍好重试",
        icon: "error",
      });
  }

  return data;
};
export default instance;
